import generating.Generate;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import packing.Packer;

/**
 * Servlet implementation class SGServlet
 */
public class SGServlet extends HttpServlet
{
	private static final long serialVersionUID = 1L;

	static final String SITE_BASE_URL = "http://cscd494-l.cslabs.ewu.edu/retral";
	
	static final String DATE = "DateHere";
	static final String INSTRUCTION = "InstructionsHere";
	static final String NUM_END = "NumEnd";
	static final String PART = "Part ";
	static final String JAR_FILE_NAME = "jar_instructions.html";
	static final String INST_FILE_NAME = "exam_instructions.html";
	static final String SCORE_SHEET = "ProgExamScoreSheetDateHere.html";
	static final String CURRENT_ID = "CurrentID";

	static final String STUDENT_PATH = "/tmp/ape/Student/";
	static final String SOLUTION_PATH = "/tmp/ape/Solution/";
	Connection conn;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public SGServlet()
	{
		super();
	}

	public void init(ServletConfig config) throws ServletException
	{
		super.init(config);
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException
	{
		final PrintWriter out = response.getWriter();
		response.setContentType("text/html");
		out.print("<html><head><title>Invalid Request</title></head><body>");
		out.print("<h1>Invalid Request</h1>");
		out
				.print("<a href=\"" + SITE_BASE_URL + "\">Return to home page</a>");
		out.print("</body></html>");
		out.flush();
		out.close();
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException
	{

		final PrintWriter out = response.getWriter();

		// out.print("Generating...<br>");
		String runCode = request.getParameter("runCode").toLowerCase();
		int examID = -1;
		try
		{
			connect();
		} catch (SQLException sql)
		{
			sql.printStackTrace();
		}

		if (runCode.compareTo("generate") == 0)
		{
			Generate gen = new Generate(conn);
			int author_id = Integer.parseInt(request.getParameter("authorID"));
			String date_scheduled = request.getParameter("examdate");
			examID = gen.generate(date_scheduled, author_id);
		} else if (runCode.compareTo("package") == 0)
		{
			Packer packer = new Packer(conn);
			examID = Integer.parseInt(request.getParameter("examID"));
			packer.pack(examID);
		}

		try
		{
			close();
		} catch (SQLException e)
		{
			e.printStackTrace();
		}

		if (runCode.compareTo("generate") == 0)
		{
			response.setContentType("text/html");
			out.print("<html><head><title>APE SourceGen</title>");
			out
					.print("<META http-equiv=\"refresh\" content=\"0;URL= " + SITE_BASE_URL + "/?page=preview&exam="
							+ examID + "\" >");
			out.print("</head><body></body></html>");
			out.flush();
			out.close();
		} else if (runCode.compareTo("package") == 0)
		{
			// out.print("<META http-equiv=\"refresh\" content=\"0;URL=" + SITE_BASE_URL + "/?page=package&exam="
			// + "");
			// out.print("<h1>Packaged Successfully</h1>");

			response.setContentType("application/octet-stream");

			String saveAsName = "ape-" + examID + ".zip";
			response.setHeader("Content-Disposition", "attachment;filename=\""
					+ saveAsName + "\"");

			FileInputStream fileInputStream = new FileInputStream(
					"/tmp/ape/ape.zip");
			int i;
			while ((i = fileInputStream.read()) != -1)
			{
				out.write(i);
			}

			fileInputStream.close();
			out.close();
		}

	}
	
	public static void main(String[] args)
	{
		String runCode = args[0];

		SGServlet sg = new SGServlet();
		try
		{
			sg.connect();
		} catch (SQLException sql)
		{
			sql.printStackTrace();
		}

		if (runCode.compareTo("generate") == 0)
		{
			if(args.length < 3) {
				printUsage();
				
			}
			else
			{
				Generate gen = new Generate(sg.conn);
			
				String date_scheduled = args[1];
				int author_id = Integer.parseInt(args[2]);
				gen.generate(date_scheduled, author_id);
			}
		} else if (runCode.compareTo("package") == 0)
		{
			if(args.length < 2) {
				printUsage();
			}
			else
			{
				Packer packer = new Packer(sg.conn);
				int examID = Integer.parseInt(args[1]);
				packer.pack(examID);
			}
		}

		try
		{
			sg.close();
		} catch (SQLException e)
		{
			e.printStackTrace();
		}
	}

	public static void printUsage() {
		System.out.println("SGServlet usage:");
		System.out.println("\tjava SGServlet generate date_created author_id");
		System.out.println("\tjava SGServlet package exam_id");
		System.out.println();
	}

	/**
	 * Connect to the oracle database
	 * 
	 * @throws SQLException
	 *             Any connection problem is not handled
	 */
	public void connect() throws SQLException
	{
		DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
		conn = DriverManager.getConnection(
				"jdbc:oracle:thin:@146.187.134.17:1542:oracle10g", "cscd494",
				"R3tral435");
	}

	/**
	 * Close the connection to database
	 * 
	 * @throws SQLException
	 *             Any connection problem is not handled
	 */
	public void close() throws SQLException
	{
		conn.close();// Close database connection
	}
}
